<template>
  <c-model v-model="show" width="750px" title="选择规格">
    <div slot="header"></div>
    <div class="sku-model">
      <i class="close-img" @click="show = false"></i>
      <div class="flex">
        <img :src="goodsItem.imgUrl || require(`@/assets/images/cover.png`)" alt="" class="goods-img">
        <div class="sku-info flex-1">
          <div class="bold fz-18 line-clamp-2 pr-50">
            {{ goodsItem.name }}
            <span class="label-new" v-if="goodsItem.isNew"/>
          </div>
          <span class="label-hot mr-10" v-if="goodsItem.isHot">热门</span>
          <span class="label-rec" v-if="goodsItem.isRecommend">推荐</span>
          <div class="goods-desc color-gray fz-12 mt-10" v-if="goodsItem.remark">
            {{ goodsItem.remark }}
          </div>
          <div class="sku-group">
            <div class="sku-group-item mt-5" v-for="(item, index) in baseList" :key="index">
              <div class="sku-group-item-name">
                <span class="color-red" v-if="item.isRequired == 1">*</span>
                {{ item.name }}：
              </div>
              <div class="sku-group-item-content">
                <div class="item"
                     :class="{'seasoning-item': child.type == 1, 'active': child.active, 'disabled': child.disabled}"
                     v-for="(child, ci) in item.children"
                     :key="ci"
                     @click.stop="checkSku(child, index)">
                  <div class="sku-name">{{ child.name }}</div>
                  <div class="sku-price price" v-if="child.type == 1">￥{{ child.price }}</div>
                </div>
              </div>
            </div>
            <div class="sku-group-item flex col-center mt-16">
              <div class="sku-group-item-name">选择数量：</div>
              <div class="sku-group-item-content flex">
                <div class="number-control flex">
                  <div class="minus iconfont icon-jian"
                       :class="{disabled: number <= 1}"
                       @click="editSkuNumber(-1)"></div>
                  <input type="number" v-model="number" style="width: 75px" @change="skuNumberChange()">
                  <div class="add iconfont icon-jia"
                       :class="{disabled: number >= goodsStock(goodsItem)}"
                       @click="editSkuNumber(1)"></div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="sku-footer flex col-center row-end">
        <!--<span class="flex col-center mr-20 line-price">原价：<span>{{ skuPrice.otTotalPrice }}</span></span>-->
        <span class="flex col-base mr-20">
          售价：<span class="price">{{ skuPrice.totalPrice }}</span>
        </span>
        <div class="sku-btn flex row-end">
          <i-button type="primary" :disabled="skuDisabled" id="skuAddCart" class="add-cart" @click="skuAddCart">
            加入购物车
          </i-button>
          <i-button type="primary" :disabled="skuDisabled" class="buy" @click="skuBuy">立即购买</i-button>
        </div>
      </div>
      <div class="package-box" v-if="packageData.length">
        <div class="package-box-head">
          <div class="label">
            <img src="@/assets/images/shop/package-label.png" alt="">
            <span>套餐商品</span>
          </div>
          <div class="package-tabs">
            <div class="item" :class="{active: packageIndex == index}"
                 v-for="(item, index) in packageData"
                 @click="packageIndex = index"
            >{{names[index]}}</div>
          </div>
        </div>
        <div class="package-box-body">
          <div class="package-list-box">
            <div class="package-list">
              <div class="item-box" v-for="(item, index) in (currPackage.children || [])" :key="index">
                <div class="item">
                  <div class="img">
                    <img src="@/assets/images/shop/main.png" alt="" class="img-main" v-if="item.isMain"/>
                    <c-image :url="item.imgUrl" alt="" width="84px" height="84px" radio="4px" />
                  </div>
                  <div class="name">{{item.name}}</div>
                  <div class="price-label">
                    <span class="price">{{item.price}}</span>
                    <span class="ot-price" v-if="item.price < item.otPrice">￥{{item.otPrice}}</span>
                  </div>
                </div>
                <div class="iconfont icon-jia plus" v-if="index < currPackage.children.length - 1"/>
              </div>
            </div>
          </div>
          <div class="handle" v-if="goodsItem.isPackage == 0">
            <div class="h-item flex row-center col-bottom">套餐价<span class="price">{{ currPackage.price }}</span></div>
            <!--<div class="h-item line-price">折扣价￥{{ currPackage.otPrice }}</div>-->
            <div class="h-item buy">
              <div class="buy-btn" @click="buyPackage()">购买套餐</div>
              <div class="add-cart-btn" id="packageAddCart" @click="addPackageCart()">加入购物车</div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div slot="footer"></div>
  </c-model>
</template>
<script>
export default {
  name: "skuModel",
  props: {
    value: {type: Boolean, default: false},
    goodsItem: {type: Object, default: {}},
    list: {type: Array, default: () => ([])},
    packageData: {type: Array, default: () => ([])},
    cartList: {type: Array, default: []},
  },
  data() {
    return {
      number: 1,
      baseList: [],
      skuList: [],
      packageIndex: 0,
      names: ['套餐A', '套餐B', '套餐C', '套餐D', '套餐E', '套餐F', '套餐G', '套餐H', '套餐I', '套餐J', '套餐K', '套餐L', '套餐M', '套餐N', '套餐O', '套餐P', '套餐Q', '套餐R', '套餐S', '套餐T', '套餐U', '套餐V', '套餐W', '套餐X', '套餐Y', '套餐Z']
    }
  },
  computed: {
    show: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit("input", val)
      }
    },
    currPackage() {
      return this.packageData[this.packageIndex] ? this.packageData[this.packageIndex] : {}
    },
    skuPrice() {
      let arr = []
      this.baseList.map(item => {
        if (item.children && item.children.length) {
          let check = item.children && item.children.filter(ch => !!ch.active)
          arr = arr.concat(check)
        }
      })
      this.skuList = arr
      if (!arr.length) {
        return {
          name: '',
          price: this.goodsItem.price,
          otPrice: this.goodsItem.otPrice,
          otTotalPrice: (this.goodsItem.otPrice * this.number).toFixed(2),
          totalPrice: (this.goodsItem.price * this.number).toFixed(2)
        }
      }
      let addPrice = arr.reduce((pre, curr) => {
        return pre + (curr.price || 0)
      }, 0)
      let names = arr.map(item => item.name)
      let price = (this.goodsItem.price + addPrice).toFixed(2)
      let otPrice = (this.goodsItem.otPrice + addPrice).toFixed(2)
      let money = (price * this.number).toFixed(2)
      let otMoney = (otPrice * this.number).toFixed(2)
      return {
        price: price,
        otPrice: otPrice,
        totalPrice: money,
        otTotalPrice: otMoney,
        names: names.join('/')
      }
    },
    skuDisabled() {
      let seasoning = this.baseList.filter(e => e.type == 1 && e.isRequired == 1)
      for (let i = 0; i < seasoning.length; i++) {
        let child = seasoning[i].children.filter(e => e.active)
        if (child.length == 0) {
          return true
        }
      }
      return false
    }
  },
  methods: {
    goodsStock(goods) {
      const number = this.cartList.reduce((pre, curr) => {
        return pre + (curr.id == goods.id ? curr.number : 0)
      }, 0)
      return goods.stockCount - number
    },
    checkSku(child, parentIndex) {
      let checkNumber = 0
      if (child.disabled) return
      let parent = this.baseList[parentIndex]
      let list = parent.children
      if (parent.type == 1) {
        checkNumber = list.reduce((pre, curr) => {
          return pre + (curr.active ? 1 : 0)
        }, 0)
        if (!child.active && checkNumber >= parent.checkNumber) {
          this.$Message.error('最多可选择' + parent.checkNumber + '个')
          return
        }
      }
      list.map(sku => {
        if (parent.type == 0) {
          if (sku.id != child.id) {
            sku.active = false
          }
        } else if (parent.type == 1) {
          if (parent.checkNumber <= 1 && !child.active) {
            sku.active = false
          }
        }
      })
      child.active = !child.active
      this.$set(this.baseList, parentIndex, parent)
    },
    editSkuNumber(number) {
      let skuNumber = this.number + number
      skuNumber = Math.max(Math.abs(skuNumber), 1)
      this.number = Math.min(skuNumber, this.goodsStock(this.goodsItem))
    },
    skuNumberChange() {
      let number = this.number
      if (!number || number < 1) number = 1
      let num = number + ''.split('.')
      num = !num[1] ? (num[0] + '.00') : num
      num = parseInt(num).toFixed(0)
      this.number = Math.min(num, this.goodsStock(this.goodsItem))
    },
    skuAddCart() {
      if (this.skuDisabled) {
        this.$Message.error('请选择加料')
        return
      }
      let number = this.number
      let skuIds = [], skuName = []
      let goodsItem = this.goodsItem
      this.skuList.map(ch => {
        skuIds.push(ch.id)
        skuName.push(ch.name)
      })
      skuIds = skuIds.join(',')
      skuName = skuName.join('/')
      this.$emit('addCart', {
        goodsItem: goodsItem,
        skuList: this.skuList,
        skuPrice: this.skuPrice,
        number: number,
        skuIds: skuIds,
        skuNames: skuName,
        packageList: goodsItem.isPackage ? this.currPackage.children : [],
        moveEl: 'skuAddCart'
      })
      this.show = false
    },
    skuBuy() {
      let skuIds = []
      let skuName = []
      this.skuList.map(ch => {
        skuIds.push(ch.id)
        skuName.push(ch.name)
      })
      skuIds = skuIds.join(',')
      skuName = skuName.join('/')
      let params = {
        goodsItem: this.goodsItem,
        skuList: this.skuList,
        number: this.number,
        skuIds: skuIds,
        skuNames: skuName,
        ...this.skuPrice,
        packageList: this.goodsItem.isPackage ? this.currPackage.children : [],
      }
      this.$emit('buy', params)
    },
    buyPackage() {  // 单品关联购买
      this.submitPackageData('buy')
    },
    addPackageCart() {  // 单品关加购
      this.submitPackageData('addCart')
    },
    submitPackageData(event) {
      let goods = Object.assign({}, this.goodsItem)
      goods.id = this.currPackage.id
      goods.name = this.currPackage.name
      goods.price = this.currPackage.price
      goods.otPrice = this.currPackage.otPrice
      goods.imgUrl = this.currPackage.imgUrl
      goods.isPackage = 1
      const price = this.currPackage.price
      let params = {
        goodsItem: goods,
        number: 1,
        price: price,
        totalPrice: price,
        packageList: this.currPackage.children || [],
        moveEl: 'packageAddCart'
      }
      this.show = false
      this.$emit(event, params)
    }
  },
  created() {
  },
  watch: {
    show(val) {
      this.packageIndex = 0
      this.number = 1
    },
    list: {
      handler(val) {
        this.baseList = val
      },
      deep: true
    }
  }
}
</script>

<style scoped lang="scss">
@import "sku";
</style>
